package com.wdd.atcrowdfunding.manager.controller;

import com.wdd.atcrowdfunding.bean.Permission;
import com.wdd.atcrowdfunding.bean.Role;
import com.wdd.atcrowdfunding.bean.User;
import com.wdd.atcrowdfunding.manager.service.PermissionService;
import com.wdd.atcrowdfunding.manager.service.RolePermissionService;
import com.wdd.atcrowdfunding.manager.service.RoleService;
import com.wdd.atcrowdfunding.manager.service.UserService;
import com.wdd.atcrowdfunding.util.AjaxResult;
import com.wdd.atcrowdfunding.util.Const;
import com.wdd.atcrowdfunding.util.Page;
import com.wdd.atcrowdfunding.util.StringUtil;
import com.wdd.atcrowdfunding.vo.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private RoleService roleService;
    @Autowired
    private PermissionService permissionService;
    @Autowired
    private RolePermissionService rolePermissionService;
    @Autowired
    private UserService userService;

    /**
     * 异步分页查询
     * @param pageno
     * @param pagesize
     * @return
     */
    @RequestMapping("/queryPageRole")
    @ResponseBody
    public AjaxResult queryPageRole(String queryText,@RequestParam(required = false, defaultValue = "1") Integer pageno,
                            @RequestParam(required = false, defaultValue = "3") Integer pagesize){
        AjaxResult ajaxResult = new AjaxResult();
        try {
            Map<String, Object> paramMap = new HashMap<String, Object>();
            paramMap.put("pageno", pageno); // 空指针异常
            paramMap.put("pagesize", pagesize);

            if(StringUtil.isNotEmpty(queryText)){
                queryText = queryText.replaceAll("%", "\\\\%"); //斜线本身需要转译
                queryText = queryText.replaceAll("_", "\\\\_");
            }

            paramMap.put("queryText", queryText);

            // 分页查询数据
            Page<Role> rolePage = roleService.queryRolePage(paramMap);
            ajaxResult.setPage(rolePage);
            ajaxResult.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            ajaxResult.setSuccess(false);
            ajaxResult.setMessage("查询数据失败");
        }
        return  ajaxResult;
    }

    @RequestMapping("/index")
    public String index(){
        return "role/index";
    }

    @RequestMapping("/assignPsermission")
    public String assignPsermission(){
        return "role/assignPsermission";
    }

    @RequestMapping("/toAdd")
    private String toAdd(){
        return "role/add";
    }

    /**
     * 添加角色
     * @param role
     * @return
     */
    @RequestMapping("/doAdd")
    @ResponseBody
    public AjaxResult doAdd(Role role){
        AjaxResult ajaxResult = new AjaxResult();
        try{
            int count = roleService.saveRole(role);
            ajaxResult.setSuccess(count==1);
        }catch (Exception e){
            e.printStackTrace();
            ajaxResult.setSuccess(false);
            ajaxResult.setMessage("角色添加失败");
        }
        return ajaxResult;
    }

    @RequestMapping("/edit")
    public String edit(Integer id,Map<String,Object> map) {
        Role role = roleService.getRoleById(id);
        map.put("role", role);
        return "role/edit";
    }

    /**
     * 删除用角色
     * @param id
     * @return
     */
    @RequestMapping("/doDelete")
    @ResponseBody
    public AjaxResult doDelete(Integer id){
        AjaxResult ajaxResult = new AjaxResult();
        try{
            int count = roleService.deleteRole(id);
            ajaxResult.setSuccess(count==1);
        }catch (Exception e){
            e.printStackTrace();
            ajaxResult.setSuccess(false);
            ajaxResult.setMessage("角色删除失败");
        }
        return ajaxResult;
    }


    /**
     * 批量删除
     * @param data
     * @return
     */
    @RequestMapping("/doDeleteBatch")
    @ResponseBody
    public AjaxResult doDeleteBatch(Data data){
        AjaxResult ajaxResult = new AjaxResult();
        try{
            int count = roleService.deleteBatchRoleByVO(data);
            ajaxResult.setSuccess(count==data.getDatas().size());
        }catch (Exception e){
            e.printStackTrace();
            ajaxResult.setSuccess(false);
            ajaxResult.setMessage("管理员删除失败");
        }
        return ajaxResult;
    }


    @ResponseBody
    @RequestMapping("/doEdit")
    public AjaxResult doEdit(Role role) {
        AjaxResult ajaxResult = new AjaxResult();
        try {
            int count = roleService.updateRole(role);// id没传的情况下,更新并不会报错,但是并没有更新成功,所以,需要加以判断
            if(count==1){
                ajaxResult.setSuccess(true);
            }else{
                ajaxResult.setSuccess(false);
            }
        } catch (Exception e) {
            e.printStackTrace();
            ajaxResult.setSuccess(false);
        }

        return ajaxResult;
    }

    /**
     * 显示分配许可树
     * @param roleid
     * @return
     */
    @ResponseBody
    @RequestMapping("/loadDataAsync")
    public Object loadDataAsync(Integer roleid, HttpSession session){
        List<Permission> root = new ArrayList<Permission>();
        List<Permission> childredPermissons =  permissionService.queryAllPermission();

        //根据角色id 查询该角色之前所分配的许可
        List<Integer> permissionIdsForRoleid = rolePermissionService.queryPermissionidsByRoleid(roleid);

        Map<Integer,Permission> map = new HashMap<Integer,Permission>();//100
        for (Permission innerpermission : childredPermissons) {
            map.put(innerpermission.getId(), innerpermission);
            if (permissionIdsForRoleid.contains(innerpermission.getId())){
                innerpermission.setChecked(true);  //会显选中复选框
            }
        }
        for (Permission permission : childredPermissons) { //100
            //通过子查找父
            //子菜单
            Permission child = permission ; //假设为子菜单
            if(child.getPid() == null ){
                root.add(permission);
            }else{
                //父节点
                Permission parent = map.get(child.getPid());
                parent.getChildren().add(child);
            }
        }

        return root ;
    }

    @RequestMapping("/assignPermission")
    public String assignPermission() {
        return "role/assignPermission";
    }


    @ResponseBody
    @RequestMapping("/doAssignPermission")
    public AjaxResult doAssignPermission(Integer roleid, Data datas) {
        AjaxResult ajaxResult = new AjaxResult();
        try {
            int count = rolePermissionService.saveRolePermissionRelationship(roleid,datas);
            ajaxResult.setSuccess(true);

        } catch (Exception e) {
            e.printStackTrace();
            ajaxResult.setSuccess(false);
        }

        return ajaxResult;
    }


}
